/*
 * CVideoRender.h
 *
 *  Created on: 2016年3月18日
 *      Author: terry
 */

#ifndef CVIDEORENDER_H_
#define CVIDEORENDER_H_

#include "VideoRender.h"
#include "VideoWindow.h"
#include "SharedPtr.h"
#include "FrameQueue.h"
#include "MultiThread.h"
#include "TimePoint.h"
#include "CommandThread.h"


namespace av
{

typedef std::shared_ptr< VideoWindow >	VideoWindowPtr;


class CVideoRender: public VideoRender, public util::CommandThread
{
public:
	CVideoRender();
	virtual ~CVideoRender();

    virtual bool getTimePoint(int64_t& clock, int64_t& pts);

	virtual void close();

	virtual bool isOpen();

	virtual int play();
	virtual int pause();
	virtual void stop();

	virtual int getState();

	virtual void setFormat(const MediaFormat& fmt);

	virtual int write(AVFramePtr frame);

	virtual void flush();

	virtual void setScale(AVRational scale);

    virtual bool setProp(const std::string& name, const std::string& value);


	virtual int open();

	virtual void setVideoWnd(void* hwnd);

	virtual bool isFullscreen();

	virtual int setFullscreen(bool full);

	virtual int setBackImage(const char* filepath);

	virtual int setRatio(int width, int height);

	virtual void getRatio(int& width, int& height);

	virtual void setRefClock(ReferenceClock* refClock);

	virtual void step();

	virtual void nextKeyFrame();

	virtual void setVideoWindow(VideoWindow* window);

protected:
	enum PlayerCommandType
	{
		kOpen = 1,
		kClose,
		kPlay,
		kPause,
		kStop,
		kSeek,
		kFlush,

		kSetScale,
		kStep,
		kNextKeyFrame,

		kFullScreen,
		kSetRatio,
		kSetImage,
		kSetVideoWnd,

		kSetVolume,
		kSetMute,

		kSetVideoFilter,

		kSnap,
		kStartRecord,
		kStopRecord
	};

protected:
	virtual void onCommand(Command& cmd);
	virtual void onIdle();

	virtual void doStop();


	void setState(StreamState state);

	AVFramePtr waitAndGet(int ms);

	int computeDelay(AVFramePtr& frame);
	void delayTime(int microseconds);

    int64_t getPts(AVFramePtr& frame);

    bool getRefPoint(TimePoint& pt);

    void handlePlay();
    void handlePause();
    void handleStop();
    void handleStep();
    void handleNextKeyFrame();
    void handleSetScale(AVRational scale);

    int64_t getClock();

protected:
	VideoWindowPtr	m_videoWindow;
	FrameQueue		m_frames;
	StreamState		m_state;
	comn::CriticalSection	m_cs;
	comn::Event		m_event;
	comn::Event		m_eventDelay;

	TimePoint	m_originPoint;
	TimePoint	m_curPoint;
	ReferenceClock*	m_refClock;
    bool    m_nosync;

    AVRational m_scale;
    bool	m_waitForKeyFrame;
    bool	m_isLive;

	int     m_ratioX;
	int     m_ratioY;

};


} /* namespace av */

#endif /* CVIDEORENDER_H_ */
